const {Controller} = require('egg');

const jwt = require('jsonwebtoken');

class UserController extends Controller{
    async login(){
        let {ctx,service} = this;

        let {username,password} = ctx.request.body;

        let hmacPwd = ctx.helper.hmac(password);

        //容错处理
        if(username && password){
            //存在
            let data = await service.user.login(username,hmacPwd);
            if(data.length){
                //查到了
                //生成token
                let token = jwt.sign({username,password,roleid:data[0].roleid},'1705b',{expiresIn:60*60})
                ctx.body = {
                    code:1,
                    token,
                    msg:'登录成功',
                    rolename:data[0].rolename
                }
            }else{
                ctx.body ={
                    code:0,
                    msg:'账号密码错误'
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数缺失'
            }
        }
    }
    //注册
    async registry(){
        let {ctx,service} = this;
        let {username,password} = ctx.request.body;
        let hmacPwd = ctx.helper.hmac(password);
        console.log("hmacPwd",hmacPwd)
        // console.log("ctx=====",ctx.helper.foo());
        try{
            await service.user.registry(username,hmacPwd);
            ctx.body = {
                code:1,
                msg:'注册成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }

    }
}

module.exports = UserController